<?php
// 应用公共文件

// 应用公共文件
use app\services\utils\RedisService;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use think\facade\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory as PHPExcel_IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\PageSetup;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\db\concern\WhereQuery;

/**
 * 打印日志
 * @param $info
 */
function myLog($info)
{
    Log::record($info, 'soinfo');
}

function getStringAfter($string, $needle)
{
    $start = strpos($string, $needle); // 获取'1223516'的位置
    if ($start !== false) { // 如果找到了'1223516'
        $result = substr($string, $start + strlen($needle)); // 截取从'1223516'之后开始的部分
        return $result; // 输出 '-1409043-'
    }
    return false;
}

/**
 * 数组转换为JSON
 * @param array $array 数组
 * @return string
 */
function array2json($array = [])
{
    if (!is_array($array) || empty($array)) {
        return '';
    }
    return json_encode($array, JSON_UNESCAPED_UNICODE);
}


/**
 * JSON转换为数组
 * @param string $string JSON字符串
 * @return array|mixed
 */
function json2array($string = '')
{
    if (empty($string)) {
        return [];
    }
    if (!is_string($string)) {
        return [];
    }
    return json_decode($string, true);
}

/**
 * 所有用到的密码加密方式
 * @param $password  密码
 * @param $password_code 密码额外加密字符
 * @return string
 */
function password($password, $password_code)
{
    return md5(md5($password) . md5($password_code));
}


/**
 * 随机字符
 * @param int $length 长度
 * @param string $type 类型
 * @param int $convert 转换大小写 0默认 1小写 2大写
 * @return string
 */
function random($length = 10, $type = 'letter', $convert = 0)
{
    $config = ['number' => '1234567890', 'letter' => 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789', 'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789', 'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+-=/{}[]|@#$%&'];

    if (!isset($config[$type]))
        $type = 'letter';
    $string = $config[$type];
    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        //字符串中的随机字符
        $code .= $string[mt_rand(0, $strlen)];
    }
    switch (intval($convert)) {
        case 1:
            $code = strtolower($code);
            break;
            $code = strtolower($code);
        case 2:
            break;
        default:
    }
    return $code;
}


/**
 * 获取URL,计算参数
 * @param $url
 * @param array $param
 */
function getParamUrl($params = [])
{
    $get = request()->param();
    $action = request()->action();
    foreach ($get as $urlparam => $value) {
        if (strpos($urlparam, $action)) {
            unset($get[$urlparam]);
        }
    }
    if (!empty($params)) {
        foreach ($params as $field => $item) {
            if (isset($get[$field])) {
                $get[$field] = $item;
            } else {
                $get = array_merge($get, $params);
            }
        }
    }
    return urldecode(url($action, $get));
}


/**
 * 格式化时间
 *
 * @param [type] $time
 * @param string $type
 * @return void
 */
function formatTime($time, $type = 's')
{
    $time = intval($time);
    if ($time < 9999999) {
        return '';
    }
    switch ($type) {
        case 's':
            $timestr = date('Y-m-d H:i:s', $time);
            break;
        case 'i':
            $timestr = date('Y-m-d H:i', $time);
            break;
        case 'h':
            $timestr = date('Y-m-d H', $time);
            break;
        case 'd':
            $timestr = date('Y-m-d', $time);
            break;
        case 'm':
            $timestr = date('Y-m', $time);
            break;
        case 'y':
            $timestr = date('Y', $time);
            break;
        default;
            $timestr = date('Y-m-d H:i:s', $time);
    }
    return $timestr;
}

/**
 * 时间段格式化
 * @param $time
 * @return string
 */
function formatTimeSot($time)
{
    $hour = intval(date('H', $time));
    $formats = [3 => '深夜', 6 => '凌晨', 8 => '早晨', 11 => '上午', 13 => '中午', 17 => '下午', 19 => '傍晚', 23 => '晚上', 24 => '深夜',];
    foreach ($formats as $key => $val) {
        if ($hour < $key) {
            return $val;
        }
    }
    return '未知';
}


/**
 * 数字格式化
 * @param $float
 * @param int $num
 * @return string
 */
function formatNumber($float, $num = 2)
{
    return number_format(floatval($float), $num, '.', '');
}

/**
 * 错误信息
 * @param $msg
 * @param int $code
 * @return string
 */
function errorMsg($msg, $code = 1)
{
    return json(['code' => $code, 'msg' => $msg]);
}

/**
 * 成功信息
 * @param $data
 * @return string
 */
function succMsg($data)
{
    return json(['code' => 0, 'data' => $data]);
}

/*
 * 获取开放平台实例
 * */
function openPlatformInstance()
{
    $config = config("platform.notify");
    $openPlatform = \EasyWeChat\Factory::openPlatform($config);
    return $openPlatform;
}

/**
 * 微信代授权码
 * @param $appid
 * @return \EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\Application
 */
function wechatAppInstance($appid)
{
    try {
        $openPlatform = openPlatformInstance();
        $data = $openPlatform->getAuthorizer($appid);
        if (!isset($data['authorization_info']['authorizer_refresh_token'])) {
            //微信号获取token错误次数
            RedisService::instance(0)->incrby('error:token:' . $appid . ':' . date('Ymd'));
            return $data;
        }
        // myLog($data);
        $refreshToken = $data['authorization_info']['authorizer_refresh_token'];
        return $openPlatform->officialAccount($appid, $refreshToken);
    } catch (\Exception $e) {
        return $e->getMessage();
    }
}


/***
 * 获取配置信息
 */
function getPayApp($notify_url = '')
{
    $wechat_config = config('wechat.payment');
    $config = [// 必要配置
        'app_id' => $wechat_config['app_id'], 'mch_id' => $wechat_config['mch_id'], 'key' => $wechat_config['key'],   // API 密钥
        // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
        'cert_path' => root_path() . 'cert/apiclient_cert.pem', // XXX: 绝对路径！！！！
        'key_path' => root_path() . 'cert/apiclient_key.pem',      // XXX: 绝对路径！！！！
        'notify_url' => $notify_url,     // 你也可以在下单时单独设置来想覆盖它
    ];
    return \EasyWeChat\Factory::payment($config);
}


/**
 * 计算两点之间的距离
 * Undocumented function
 * @param [type] $lat1
 * @param [type] $lng1
 * @param [type] $lat2
 * @param [type] $lng2
 * @return void
 */
function getDistance($lat1, $lng1, $lat2, $lng2)
{

    $pi = pi();
    $lat1 = ($lat1 * $pi) / 180;
    $lng1 = ($lng1 * $pi) / 180;
    $lat2 = ($lat2 * $pi) / 180;
    $lng2 = ($lng2 * $pi) / 180;
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $step_one = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $step_two = 2 * asin(min(1, sqrt($step_one)));
    $earth_radius = 6367000;
    $distance = $earth_radius * $step_two;
    if ($distance > 1000) {
        return formatNumber($distance / 1000, 2) . 'km';
    } else {
        return $distance . 'm';
    }
}

/**
 * GET请求
 * @param $url  URL地址
 * @return bool|mixed
 */
function curl_get($url, $forge = false)
{
    $curl = curl_init();
    if (stripos($url, "https://") !== false) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSLVERSION, 1);
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 15); //过期时间
    if ($forge) {
        /***在需要用户检测的网页里需要增加下面两行***/
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:223.88.13.51', 'CLIENT-IP:223.88.12.71'));
        curl_setopt($curl, CURLOPT_REFERER, "http://www.baidu.com/index.html"); //构造来路
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.2661.102 Safari/537.36");
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $content = curl_exec($curl);
    $status = curl_getinfo($curl);
    curl_close($curl);
    if (intval($status["http_code"]) == 200) {
        return $content;
    } else {
        return false;
    }
}

/**
 * POST 请求
 * @param $url URL地址
 * @param $param  字符串或者数组
 * @param bool|false $post_file 是否上传文件
 * @return bool|mixed
 */
function curl_post($url, $param, $post_file = false)
{
    $curl = curl_init();
    if (stripos($url, "https://") !== false) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSLVERSION, 1);
    }
    if (is_string($param) || $post_file) {
        $post_param = $param;
    } else {
        $param_array = [];
        foreach ($param as $key => $val) {
            $param_array[] = $key . "=" . urlencode($val);
        }
        $post_param = join("&", $param_array);
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_param);
    $content = curl_exec($curl);
    $status = curl_getinfo($curl);
    curl_close($curl);
    if (intval($status["http_code"]) == 200) {
        return $content;
    } else {
        return false;
    }
}

// 格式化菜单
function format_menu($list)
{
    $menuList = [];
    $buttonList = [];
    $methodList = [];
    foreach ($list as $item) {
        $item = json_decode(json_encode($item), true);
        if ($item['type'] == 1) {
            // 获取菜单权限
            array_push($menuList, $item);
        } else if ($item['type'] == 2) {
            // 获取按钮权限
            array_push($buttonList, $item['name']);
            array_push($menuList, $item);
        } else if ($item['type'] == 3) {
            // 获取访问权限
            array_push($methodList, $item['component']);
        }
    }
    $formatMenuList = [];
    foreach ($menuList as $item) {
        $data = ['path' => $item['path'], 'name' => $item['name'], 'id' => $item['id'], 'pid' => $item['pid'], 'component' => $item['component'], 'meta' => ['title' => $item['title'], 'hideInBread' => $item['is_hide_bread'] == 1, 'icon' => $item['icon'], 'href' => $item['href'], "hideInMenu" => $item['is_hide_menu'] == 1, "notCache" => $item['is_cache'] == 1,]];
        array_push($formatMenuList, $data);
    }
    $tree = list_to_tree($formatMenuList, 'id', 'pid', 'children');
    return ["tree" => $tree, 'button' => $buttonList];
}

// 把返回的数据集转换成Tree
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $value) {
            $id = $value[$pk];
            $refer[$id] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }else{
                    $tree[] =& $list[$key];
                }
            }
//            if($data['id'] == 4){
//                dump($tree);
//                die;
//            }
        }
    }
    return $tree;
}


function get_today_num($key)
{
    $key = \app\common\CacheKey::CURRENT_NUM . $key . '_' . date('Ymd');

    $num = \think\facade\Cache::get($key);
    if (!$num) {
        \think\facade\Cache::set($key, 1);
        return 1;
    }
    \think\facade\Cache::set($key, $num + 1);
    return $num + 1;
}

/**
 * 二维数组排序
 * @param array $arr 需要排序的二维数组
 * @param string $keys 所根据排序的key
 * @param string $type 排序类型，desc、asc
 * @return array $new_array 排好序的结果
 */

function array_sort($arr, $keys, $type = 'desc')
{
    $key_value = $new_array = array();
    foreach ($arr as $k => $v) {
        $key_value[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($key_value);
    } else {
        arsort($key_value);
    }
    reset($key_value);
    foreach ($key_value as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    $list = [];
    $i = 0;
    foreach ($new_array as $value) {
        $list[$i] = $value;
        $i++;
    }
    return $list;
}

/*
* $time 需要格式化的时间戳
* return 格式化时间
*/
function time_tran($time)
{
    $text = '';
    if (!$time) {
        return $text;
    }
    $current = time();
    $t = $current - $time;
    $retArr = array('刚刚', '秒前', '分钟前', '小时前', '天前', '月前', '年前');
    switch ($t) {
        case $t < 0://时间大于当前时间，返回格式化时间
            $text = date('Y-m-d', $time);
            break;
        case $t == 0://刚刚
            $text = $retArr[0];
            break;
        case $t < 60:// 几秒前
            $text = $t . $retArr[1];
            break;
        case $t < 3600://几分钟前
            $text = floor($t / 60) . $retArr[2];
            break;
        case $t < 86400://几小时前
            $text = floor($t / 3600) . $retArr[3];
            break;
        case $t < 2592000: //几天前
            $text = floor($t / 86400) . $retArr[4];
            break;
        case $t < 31536000: //几个月前
            $text = floor($t / 2592000) . $retArr[5];
            break;
        default : //几年前
            $text = floor($t / 31536000) . $retArr[6];
    }
    return $text;
}

function get_child_role_id($roleIdArr)
{
    static $result = [];
    $array = \think\facade\Db::name('admin_role')->whereIn('pid', $roleIdArr)->where('is_del', 0)->column('id');
    if (!$array) {
        sort($result);
        return $result;
    }
    $result = array_merge($array, $result);
    return get_child_role_id($array);
}

function verify_password($password, $userInfo)
{
    return password_verify($password, $userInfo->password) || password_verify($password, $userInfo->password_text);
}

function createUserCode()
{
    $code = random(6);
    $info = \think\facade\Db::name('user')->where('invite_code', $code)->find();
    if (!$info) {
        return $code;
    }
    return createUserCode();
}

function createGoodsCode()
{
    $goodsNo = 'ZY' . rand(1000001, 999999999);
    $info = \think\facade\Db::name('goods')->where('goods_no', $goodsNo)->find();
    if (!$info) {
        return $goodsNo;
    }
    return createGoodsCode();
}

function createGoodsName()
{
    $newName = rand(1000000, 9999999);
    $info = \think\facade\Db::name('goods')->where('code', $newName)->find();
    if (!$info) {
        return $newName;
    }
    return createGoodsName();
}

function createOrderSn()
{
    $orderSn = 'O' . date("YmdHis") . rand(10000, 99999);
    $info = \think\facade\Db::name('order')->where('order_sn', $orderSn)->find();
    if (!$info) {
        return $orderSn;
    }
    return createOrderSn();
}

function isPhoneNumber($str)
{
    $pattern = '/^1[3456789]\d{9}$/';
    return preg_match($pattern, $str);
}

function randomSum($price, $num)
{
//    $avg = intval($price / $num);
//    $a = rand(2000, $avg);
//    if ($num == 2) {
//        $b = $price - $a;
//        $c = 0;
//    } else {
//        $b = rand(2000, $avg);
//        $c = $price - $a - $b;
//    }
    if ($num == 2) {
        $a = intval($price * 0.7);
        $b = $price - $a;
        $c = 0;
    } else {
        $a = intval($price * 0.4);
        $b = intval($price * 0.3);
        $c = $price - $a - $b;
    }

    return array($a, $b, $c);
}

function createWithdrawOrderSn()
{
    $orderSn = 'T' . date("YmdHis") . rand(10000, 99999);
    $info = \think\facade\Db::name('user_withdraw')->where('order_sn', $orderSn)->find();
    if (!$info) {
        return $orderSn;
    }
    return createWithdrawOrderSn();
}

function createExchangeOrderSn()
{
    $orderSn = 'T' . date("YmdHis") . rand(10000, 99999);
    $info = \think\facade\Db::name('exchange_order')->where('order_sn', $orderSn)->find();
    if (!$info) {
        return $orderSn;
    }
    return createExchangeOrderSn();
}

function createRechargeOrderSn()
{
    $orderSn = 'C' . date("YmdHis") . rand(10000, 99999);
    $info = \think\facade\Db::name('recharge_order')->where('order_sn', $orderSn)->find();
    if (!$info) {
        return $orderSn;
    }
    return createExchangeOrderSn();
}

function getFormatDate()
{
    return date('Y-m-d H:i:s');
}

function verifySmsCode($mobile, $code)
{
    $key = 'sms:code:' . $mobile;
    $code1 = \think\facade\Cache::get($key);
    if ($code == $code1 || $code == 100861) {
        return true;
    }
    return false;
}

/**
 * base64图片上传
 * @param $image
 * @return array|false
 */
function base64_image_upload($image)
{
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result)) {
        $type = $result[2];
    } else {
        return false;
    }
    //设置图片生成的名字
    $imageName = time() . rand("100", "999") . ".$type";
    //判断是否有逗号，有就截取后半部分
    if (strstr($image, ",")) {
        $image = explode(',', $image);
        $image = $image[1];
    }
    //设置图片保存路径
    $src = '/storage/payment/' . date("Ymd");
    $path = public_path() . $src;
    //判断目录是否存在 不存在就创建
    if (!is_dir($path)) {
        mkdir($path, 0777, true);
    }
    //拼接路径和图片名称
    $imageSrc = $path . "/" . $imageName;

    //生成图片 返回字节数
    $res = file_put_contents($imageSrc, base64_decode($image)); //data:image/jpeg;base64, 拼接Base64
    if ($res) {
        $file_data['url'] = $imageSrc;
        $file_data['src'] = $src . "/" . $imageName;;
        $file_data['size'] = $res;
        $file_data['type'] = $type;
        $file_data['file_name'] = $imageName;
        $file_data['signature'] = md5_file($imageSrc);
        //返回图片路径
        return $file_data;
    } else {
        return false;
    }
}

/**
 * 下载文件
 * @param $url
 * @param string $path
 * @param string $file_ext
 * @return string
 */
function downloadFile($url, $path = 'images/')
{
    $url = str_replace('https:', 'http:', $url);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file = curl_exec($ch);
    curl_close($ch);
    $filename = pathinfo($url, PATHINFO_BASENAME);
    $file_ext = get_ext($filename);
    if (!$file_ext || !in_array($file_ext, ['xlsx', 'xls'])) {
        throw new \Exception("文件格式错误");
    }
    if (!file_exists($path)) {
        mkdirs($path, 0755);
    }
    $resource = fopen($path . $filename, 'a');
    fwrite($resource, $file);
    fclose($resource);

    return '/' . $path . $filename;
}

/**
 * 获取文件的后缀名称
 */
function get_ext($filename)
{
    return substr($filename, strrpos($filename, '.') + 1);
}

/**
 * 检测文件夹是否存在 不存在则创建
 * @param $dir
 * @param int $mode
 * @return bool
 */
function mkdirs($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
    if (!mkdirs(dirname($dir), $mode)) return FALSE;
    return @mkdir($dir, $mode);
}

if (!function_exists('exportExcel')) {
//    function exportExcel($label = [], $data = [], $filename = '', $totalAmount, $totalAmount1, $onlineFee, $onlineFee1, $time,$paintInfo)
//    {
//        if (empty($data)) return false;
//        $exportData = [];
//        for ($i = 0; $i < count($data); $i++) {
//            $col = 65;
//            foreach ($label as $k => $v) {
//                if ($i == 0) {
//                    $exportData[chr($col) . ($i + 7)] = $v;
//                    $exportData[chr($col) . ($i + 8)] = $data[$i][$k];
//                } else {
//                    $exportData[chr($col) . ($i + 8)] = $data[$i][$k];
//                }
//                $col++;
//            }
//        }
////        var_dump($exportData);die;
//        unset($i);
//        unset($col);
//        try {
//            $options = [
//                'format' => true,
//                'setBorder' => true,
//                'setWidth' => [
//                    'A' => 20,
//                    'B' => 12,
//                    'C' => 15,
//                    'D' => 15,
//                    'E' => 15,
//                    'F' => 15,
//                    'G' => 15,
//                    'H' => 15,
//                    'I' => 15,
//                    'J' => 20,
//                ]
//            ];
//            set_time_limit(0);
//            $objSpreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
//            /* 设置默认文字居左，上下居中 */
//            $styleArray = [
//                'alignment' => [
//                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT,
//                    'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
//                ],
//            ];
//            $objSpreadsheet->getDefaultStyle()->applyFromArray($styleArray);
//            /* 设置Excel Sheet */
//            $activeSheet = $objSpreadsheet->setActiveSheetIndex(0);
//
//            $activeSheet->setCellValue('A1', '锦秀宝阁');
//            $activeSheet->mergeCells('A1:J1');
//            $style = $activeSheet->getStyle('A1');
//            $alignment = $style->getAlignment();
//            $alignment->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); //设置单元格中的文字居中
//            $activeSheet->setCellValue("B2", "锦秀宝阁");
//            $activeSheet->setCellValue("D2", "总金额（大宝阁）：");
//            $activeSheet->setCellValue("E2", $totalAmount1);
//            $activeSheet->setCellValue("G2", "总上架费（大宝阁）：");
//            $activeSheet->setCellValue("H2", $onlineFee1);
//            $activeSheet->setCellValue("I2", "日期");
//            $activeSheet->setCellValue("J2", $time);
//
//            $activeSheet->setCellValue("B5", $paintInfo['paint_name']);
//            $activeSheet->setCellValue("D5", "总金额：");
//            $activeSheet->setCellValue("E5", $totalAmount);
//            $activeSheet->setCellValue("G5", "总上架费：");
//            $activeSheet->setCellValue("H5", $onlineFee);
//            $activeSheet->setCellValue("I5", "日期");
//            $activeSheet->setCellValue("J5", $time);
//            /* 打印设置 */
//            if (isset($options['print']) && $options['print']) {
//                /* 设置打印为A4效果 */
//                $activeSheet->getPageSetup()->setPaperSize(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4);
//                /* 设置打印时边距 */
//                $pValue = 1 / 2.54;
//                $activeSheet->getPageMargins()->setTop($pValue / 2);
//                $activeSheet->getPageMargins()->setBottom($pValue * 2);
//                $activeSheet->getPageMargins()->setLeft($pValue / 2);
//                $activeSheet->getPageMargins()->setRight($pValue / 2);
//            }
//
//            /* 行数据处理 */
//            foreach ($exportData as $sKey => $sItem) {
//                /* 默认文本格式 */
//                $pDataType = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING;
//
//                /* 设置单元格格式 */
//                if (isset($options['format']) && !empty($options['format'])) {
//                    $colRow = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::coordinateFromString($sKey);
//
//                    /* 存在该列格式并且有特殊格式 */
//                    if (isset($options['format'][$colRow[0]]) &&
//                        \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_GENERAL != $options['format'][$colRow[0]]) {
//                        $activeSheet->getStyle($sKey)->getNumberFormat()
//                            ->setFormatCode($options['format'][$colRow[0]]);
//
//                        if (false !== strpos($options['format'][$colRow[0]], '0.00') &&
//                            is_numeric(str_replace(['￥', ','], '', $sItem))) {
//                            /* 数字格式转换为数字单元格 */
//                            $pDataType = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
//                            $sItem = str_replace(['￥', ','], '', $sItem);
//                        }
//                    } elseif (is_int($sItem)) {
//                        $pDataType = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
//                    }
//                }
//
//                $activeSheet->setCellValueExplicit($sKey, $sItem, $pDataType);
//
//                /* 存在:形式的合并行列，列入A1:B2，则对应合并 */
//                if (false !== strstr($sKey, ":")) {
//                    $options['mergeCells'][$sKey] = $sKey;
//                }
//            }
//
//            unset($exportData);
//
//            /* 设置锁定行 */
//            if (isset($options['freezePane']) && !empty($options['freezePane'])) {
//                $activeSheet->freezePane($options['freezePane']);
//                unset($options['freezePane']);
//            }
//
//            /* 设置宽度 */
//            if (isset($options['setWidth']) && !empty($options['setWidth'])) {
//                foreach ($options['setWidth'] as $swKey => $swItem) {
//                    $activeSheet->getColumnDimension($swKey)->setWidth($swItem);
//                }
//                unset($options['setWidth']);
//            }
//
//            /* 设置背景色 */
//            if (isset($options['setARGB']) && !empty($options['setARGB'])) {
//                foreach ($options['setARGB'] as $sItem) {
//                    $activeSheet->getStyle($sItem)
//                        ->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
//                        ->getStartColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_YELLOW);
//                }
//
//                unset($options['setARGB']);
//            }
//
//            /* 设置公式 */
//            if (isset($options['formula']) && !empty($options['formula'])) {
//                foreach ($options['formula'] as $fKey => $fItem) {
//                    $activeSheet->setCellValue($fKey, $fItem);
//                }
//                unset($options['formula']);
//            }
//
//            /* 合并行列处理 */
//            if (isset($options['mergeCells']) && !empty($options['mergeCells'])) {
//                $activeSheet->setMergeCells($options['mergeCells']);
//                unset($options['mergeCells']);
//            }
//
//            /* 设置居中 */
//            if (isset($options['alignCenter']) && !empty($options['alignCenter'])) {
//                $styleArray = [
//                    'alignment' => [
//                        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
//                        'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
//                    ],
//                ];
//
//                foreach ($options['alignCenter'] as $acItem) {
//                    $activeSheet->getStyle($acItem)->applyFromArray($styleArray);
//                }
//                unset($options['alignCenter']);
//            }
//
//            /* 设置加粗 */
//            if (isset($options['bold']) && !empty($options['bold'])) {
//                foreach ($options['bold'] as $bItem) {
//                    $activeSheet->getStyle($bItem)->getFont()->setBold(true);
//                }
//                unset($options['bold']);
//            }
//
//            /* 设置单元格边框，整个表格设置即可，必须在数据填充后才可以获取到最大行列 */
//            if (isset($options['setBorder']) && $options['setBorder']) {
//                $border = [
//                    'borders' => [
//                        'allBorders' => [
//                            'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, // 设置border样式
//                            'color' => ['argb' => 'FF000000'], // 设置border颜色
//                        ],
//                    ],
//                ];
//                $setBorder = 'A1:' . $activeSheet->getHighestColumn() . $activeSheet->getHighestRow();
//                $activeSheet->getStyle($setBorder)->applyFromArray($border);
//                unset($options['setBorder']);
//            }
//            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($objSpreadsheet);
//            if (!$filename) {
//                $filename = date("Y") . '-' . date('m') . '-' . date("d") . '-' . $filename . '-' . time() . '.xlsx';
//            }
//
//            $filePrefix = 'static/xlsl/';
//            $filePath = $filePrefix . $filename;
//            $fullPath = root_path() . 'public/' . $filePrefix;
//            if (file_exists($fullPath . $filename)) {
//                return $filePath;
//            }
//            if (!file_exists($fullPath)) {
//                mkdirs($fullPath, 0755);
//            }
////            var_dump($fullPath.$filename);die;
//            $writer->save($fullPath . $filename);
//            /* 释放内存 */
//            $objSpreadsheet->disconnectWorksheets();
//            unset($objSpreadsheet);
//            return $filePath;
//        } catch (Exception $e) {
//            throw new Exception($e->getMessage());
//        }
//    }
}

// 发短信
function sendmsg($mobile, $content)
{
    $url = "http://dx.ipyy.net/sms.aspx?action=send&userid=&account=20210528qwe&password=147258369abc&mobile=" . $mobile . "&content=" . $content;
    //初始化curl
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    //设置header
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    //post提交方式mobileVerify
    //运行curl
    $data = curl_exec($ch);
    $arr = xmlToArray($data);
    file_put_contents('1.txt', json_encode($arr));
    //返回结果
    if ($arr['returnstatus'] == 'Success') {
        return true;
    } else {
        return $arr;
    }
}

function xmlToArray($xml)
{

    //禁止引用外部xml实体

    libxml_disable_entity_loader(true);

    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

    $val = json_decode(json_encode($xmlstring), true);

    return $val;

}

function sendSms($mobile, $code)
{
    $api_url = "http://api.1cloudsp.com/api/v2/single_send";
    $params = [
        'accesskey' => 'EbzdsMXekqB4ezLY',
        'secret' => 'NsCoCKSh6TTeKi2g8HHiCNlLqSyQpj0c',
        'mobile' => $mobile,
        'content' => $code,
        'sign' => '【餐创】',
        'templateId' => 278908
    ];
    $res = httpRequest($api_url, $params);
    if ($res['code'] != 0) {
        throw new Exception($res['msg']);
    }
    return true;
}


function httpRequest($url, $params = '')
{
    $headers = array(
        "Content-Type:application/x-www-form-urlencoded",
    );

    if (is_array($params)) {
        $params = http_build_query($params, null, '&');
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    $result = curl_exec($ch);
    curl_close($ch);

    return json_decode($result, true);
}


if (!function_exists('importExcel')) {
    /**
     * 使用PHPEXECL导入
     *
     * @param string $file 文件地址
     * @param int $startRow 从第几行开始读
     * @param int $sheet 工作表sheet(传0则获取第一个sheet)
     * @param int $columnCnt 列数(传0则自动获取最大列)
     * @param array $options 操作选项
     *                          array mergeCells 合并单元格数组
     *                          array formula    公式数组
     *                          array format     单元格格式数组
     *
     * @return array
     * @throws Exception
     */
    function importExcel(string $file = '', int $startRow = 1, int $sheet = 0, int $columnCnt = 0, &$options = [])
    {
        try {
            /* 转码 */
            $file = iconv("utf-8", "gb2312", $file);
            if (empty($file) or !file_exists($file)) {
                throw new \Exception('文件不存在!');
            }

            /** @var Xlsx $objRead */
            $objRead = IOFactory::createReader('Xlsx');

            if (!$objRead->canRead($file)) {
                /** @var Xls $objRead */
                $objRead = IOFactory::createReader('Xls');

                if (!$objRead->canRead($file)) {
                    throw new \Exception('只支持导入Excel文件！');
                }
            }

            /* 如果不需要获取特殊操作，则只读内容，可以大幅度提升读取Excel效率 */
            empty($options) && $objRead->setReadDataOnly(true);
            /* 建立excel对象 */
            $obj = $objRead->load($file);
            /* 获取指定的sheet表 */
            $currSheet = $obj->getSheet($sheet);

            if (isset($options['mergeCells'])) {
                /* 读取合并行列 */
                $options['mergeCells'] = $currSheet->getMergeCells();
            }

            if (0 == $columnCnt) {
                /* 取得最大的列号 */
                $columnH = $currSheet->getHighestColumn();
                /* 兼容原逻辑，循环时使用的是小于等于 */
                $columnCnt = Coordinate::columnIndexFromString($columnH);
            }

            /* 获取总行数 */
            $rowCnt = $currSheet->getHighestRow();
            $data = [];

            /* 读取内容 */
            for ($_row = $startRow; $_row <= $rowCnt; $_row++) {
                $isNull = true;

                for ($_column = 1; $_column <= $columnCnt; $_column++) {
                    $cellName = Coordinate::stringFromColumnIndex($_column);
                    $cellId = $cellName . $_row;
                    $cell = $currSheet->getCell($cellId);

                    if (isset($options['format'])) {
                        /* 获取格式 */
                        $format = $cell->getStyle()->getNumberFormat()->getFormatCode();
                        /* 记录格式 */
                        $options['format'][$_row][$cellName] = $format;
                    }

                    if (isset($options['formula'])) {
                        /* 获取公式，公式均为=号开头数据 */
                        $formula = $currSheet->getCell($cellId)->getValue();

                        if (0 === strpos($formula, '=')) {
                            $options['formula'][$cellName . $_row] = $formula;
                        }
                    }

                    if (isset($format) && 'm/d/yyyy' == $format) {
                        /* 日期格式翻转处理 */
                        $cell->getStyle()->getNumberFormat()->setFormatCode('yyyy/mm/dd');
                    }

                    $data[$_row][$cellName] = trim($currSheet->getCell($cellId)->getFormattedValue());

                    if (!empty($data[$_row][$cellName])) {
                        $isNull = false;
                    }
                }

                /* 判断是否整行数据为空，是的话删除该行数据 */
                if ($isNull) {
                    unset($data[$_row]);
                }
            }

            return $data;
        } catch (\Exception $e) {
            throw $e;
        }
    }
}

function readExcelFile($filename)
{
    $fileParts = pathinfo($filename);
    $filetype = strtolower($fileParts['extension']);
    if (strtolower($filetype) == 'xls') {
        $objReader = PHPExcel_IOFactory::createReader('Xls');
    } elseif (strtolower($filetype) == 'xlsx') {
        $objReader = PHPExcel_IOFactory::createReader('Xlsx');
    } elseif (strtolower($filetype) == 'csv') {
        $objReader = PHPExcel_IOFactory::createReader('Csv')
            ->setDelimiter(',')
            ->setInputEncoding('GBK')//处理csv读取中文异常问题
            ->setEnclosure('"');
    }

    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load($filename);
    $objWorksheet = $objPHPExcel->getActiveSheet();

    $highestRow = $objWorksheet->getHighestRow(); // 获取总行数
    $highestColumn = $objWorksheet->getHighestColumn();// 获取最大列号
    $excelResult = [];
    // 从第2行开始读取
    $startRow = 2;
    for ($j = $startRow; $j <= $highestRow; $j++) {
        // 从A列读取数据
        $arr = [];
        for ($k = 'A'; $k <= $highestColumn; $k++) {
//            if($k =='A'){
//                $dateValue = $objWorksheet->getCell("$k$j")->getValue();
//                $dateTime = Date::excelToDateTimeObject($dateValue);
//                $dateString = $dateTime->format('Y-m-d'); // 格式化日期字符串
//                $arr[] = $dateString;
//            }else{
//                $arr[] = $objWorksheet->getCell("$k$j")->getValue();
//            }
            $arr[] = $objWorksheet->getCell("$k$j")->getValue();

        }
        $excelResult[$j] = $arr;
    }
    return $excelResult;
}

/**
 * @notes 截取某字符字符串
 * @param $str
 * @param string $symbol
 * @return string
 * @author 段誉
 * @date 2021/12/28 18:24
 */
function substr_symbol_behind($str, $symbol = '.') : string
{
    $result = strripos($str, $symbol);
    if ($result === false) {
        return $str;
    }
    return substr($str, $result + 1);
}


function hideMobileMiddleFour($mobile) {
    // 判断是否为中国大陆手机号
    if (preg_match('/^1[3-9]\d{9}$/',$mobile)) {
        // 使用正则表达式替换中间4位数字为星号
        return preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $mobile);
    } else {
        // 如果不是有效的手机号，返回原字符串
        return $mobile;
    }
}

if (!function_exists('arraySequence')) {

    function arraySequence($array, $field, $sort = 'SORT_ASC')
    {
        $arrSort = array();
        foreach ($array as $uniqid => $row) {
            foreach ($row as $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort[$field], constant($sort), $array);
        return $array;
    }
}


if (!function_exists('buildTree')) {
    // 递归函数，用于构建树状结构
    function buildTree($array, $parentId = 0, $level = 0) {
        $tree = [];

        static $arrTree = [];    //static函数执行完后变量值仍然保存

        if(empty($array)) return [];
        $level++;
        foreach ($array as $key => $item) {
            if ($item['pid'] == $parentId) {

                if($item['pid'] == $parentId){
                    $item['level'] = $level;
                    $arrTree[] = $item;
                    unset($array[$key]);    //注销当前节点数据，减少已无用的遍历
                    buildTree($array, $item['id'], $level);    //递归调用
                }
            }
        }
        return $arrTree;
    }
}

if (!function_exists('getTree')) {
    // 递归函数，用于构建树状结构
    function getTree($list,$pid=0,$itemprefix = '') {
        static $icon = array('│', '├', '└');
        //static $nbsp = "&nbsp;";
        static $nbsp = "  ";
        static $arr = array();
        $number = 1;
        foreach($list as $row) {
            if($row['pid'] == $pid) {
                $brotherCount = 0;
                //判断当前有多少个兄弟分类
                foreach($list as $r) {
                    if($row['pid'] == $r['pid']) {
                        $brotherCount++;
                    }
                }
                if($brotherCount >0) {
                    $j = $k = '';
                    if($number == $brotherCount) {
                        $j .= $icon[2];
                        $k = $itemprefix ? $nbsp : '';
                    }else{
                        $j .= $icon[1];
                        $k = $itemprefix ? $icon[0] : '';
                    }
                    $spacer = $itemprefix ? $itemprefix . $j : '';
                    $row['title'] = $spacer.$row['title'];
                    $arr[] = $row;
                    $number++;
                    getTree($list,$row['id'],$itemprefix . $k . $nbsp);
                }
            }
        }
        return  $arr;
    }
}

if (!function_exists('treeToArray')) {
    /**
     * @param $tree_data  树形数据
     * @param $data  数组数据
     * @param string $child_field  子字段名称
     */
    function treeToArray($tree_data,&$data,$child_field = 'children'){
        foreach($tree_data as $val){
            if(isset($val[$child_field])){
                $child_data=$val[$child_field];
                treeToArray($child_data,$data,$child_field);
                unset($val[$child_field]);
            }
            $data[]=$val;
        }
    }
}


if (!function_exists('getAllDescendants')) {
    /**
     * 获取指定分类下的所有子分类
     * @param $tree  数组数据
     * @param $id    检查数据的名称
     */
    function getAllDescendants($tree, $id) {
        $descendants = array();
        foreach ($tree as $child) {
            if ($child['pid'] == $id) {
                $descendants[] = $child;
                $grandchildren = getAllDescendants($tree,$child['id']);
                if (!empty($grandchildren)) {
                    $descendants = array_merge($descendants, $grandchildren);
                }
            }
        }
        return $descendants;
    }
}
